package com.cn.tcc;

import com.cn.entity.Account;
import com.cn.mapper.AccountMapper;
import com.cn.service.AccountServiceImpl;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Component
public class AccountTCCActionImpl implements AccountTCCAction {
    @Autowired
    private AccountMapper accountMapper;
    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long userId, BigDecimal money) {
        Account account= accountMapper.selectById(userId);
        if (money.compareTo(account.getResidue())>0){
            throw new RuntimeException("没钱");
        }
        accountMapper.updateFrozen(userId, money);
        ResultHolder.setResult(AccountServiceImpl.class, ctx.getXid(), "p");
        return true;
    }
    @Transactional

    @Override
    public boolean commit(BusinessActionContext ctx, Long userId, BigDecimal money) {
        if (ResultHolder.getResult(AccountServiceImpl.class, ctx.getXid())==null){
            return true;
        }
        userId=Long.valueOf(ctx.getActionContext("userId").toString());
        money=BigDecimal.valueOf(Long.parseLong(ctx.getActionContext("money").toString()));
        accountMapper.updateFrozenToUsed(userId, money);

        return true;
    }
    @Transactional

    @Override
    public boolean rollback(BusinessActionContext ctx, Long userId, BigDecimal money) {
        if (ResultHolder.getResult(AccountServiceImpl.class, ctx.getXid())==null){
            return true;
        }
        userId=Long.valueOf(ctx.getActionContext("userId").toString());
        money=BigDecimal.valueOf(Long.parseLong(ctx.getActionContext("money").toString()));
        accountMapper.updateFrozenToResidue(userId, money);

        return true;
    }
}
